﻿using System.Collections.Generic;
using System.Data.SQLite;
using System.IO;
using System.Linq;

namespace HandTest
{
    partial class MainWindow
    {
        SQLiteConnection connectionToCardsDatabase;
        List<string> cardsInMainDeck;
        readonly Dictionary<string, string> idToNames = new Dictionary<string, string>();

        void LoadDeckFile(FileInfo deckFile)
        {
            using (StreamReader sr = deckFile.OpenText())
            {
                if (connectionToCardsDatabase.State != System.Data.ConnectionState.Open)
                {
                    connectionToCardsDatabase.Open();
                    SQLiteCommand cmd = new SQLiteCommand { Connection = connectionToCardsDatabase };
                    var selectfrom = "SELECT name FROM texts where id == ";

                    string s;
                    cardsInMainDeck = new List<string>();
                    while ((s = sr.ReadLine()) != null)
                    {
                        if (s.Equals("#extra") || s.Equals("!side"))
                            break;
                        else if (numRegex.IsMatch(s))
                        {
                            cmd.CommandText = selectfrom + s;
                            SQLiteDataReader sdr = cmd.ExecuteReader();
                            if (sdr.Read())
                            {
                                var name = sdr[0].ToString();
                                if (!idToNames.ContainsKey(s))
                                    idToNames.Add(s, name);
                                cardsInMainDeck.Add(name);
                            }
                            sdr.Close();
                        }
                    }
                    mainDeckLabel.Content = "主卡组：" + cardsInMainDeck.Count() + "张";
                    mainDeckListBox.ItemsSource = cardsInMainDeck;
                }
                connectionToCardsDatabase.Close();
            }
        }

        void LoadDeckFileList()
        {
            if (Directory.Exists(ygoFolder + "deck\\"))
            {
                deckDirectory = new DirectoryInfo(ygoFolder + "deck\\");
                deckFileList.ItemsSource = deckDirectory.GetFiles("*.ydk");
                connectionToCardsDatabase = new SQLiteConnection("data source=" + ygoFolder + "cards.cdb");
            }
        }
    }
}
